package com.bw.controller;

import cn.hutool.core.util.NumberUtil;
import com.bw.entity.ApplyInfo;
import com.bw.entity.ApplyQuery;
import com.bw.entity.Dict;
import com.bw.mapper.ApplyMapper;
import com.bw.service.ApplyService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.validation.Valid;
import java.util.List;

@Controller
public class ApplyController {

    @Autowired
    ApplyMapper applyMapper;
    @Autowired
    ApplyService applyService;

    @RequestMapping("/list.do")
    public String list(ApplyQuery query, Integer pageNum, Model model) {
        // 1. 渲染下拉框
        //1. 渲染 单选框
        List<Dict> typeList = applyMapper.listType();
        model.addAttribute("typeList", typeList);
        // 2. 分页查询

        PageHelper.startPage(pageNum == null ? 1 : pageNum, 3);
        List<ApplyInfo> list = applyMapper.selectByQuery(query);

        PageInfo<ApplyInfo> pageInfo = new PageInfo<>(list);

        model.addAttribute("pageInfo", pageInfo);
        //条件回显
        model.addAttribute("query", query);


        return "list";
    }

    /**
     * 完成报销
     *
     * @param id
     * @return
     */
    @RequestMapping("/changeStatus.do")
    public String changeStatus(Integer id) {

        // 根据id 修改报销状态
        applyMapper.updateStatus(id);

        return "redirect:list.do";

    }

    /**
     * 添加页面
     *
     * @return
     */
    @RequestMapping("/addPage.do")
    public String addPage(Model model) {

        //1. 渲染 单选框
        List<Dict> typeList = applyMapper.listType();
        model.addAttribute("typeList", typeList);
        return "add";

    }


    /**
     * 执行添加
     *
     * @return
     */
    @RequestMapping("/add.do")
    public String add(@Valid ApplyInfo applyInfo, BindingResult result, Model model) {
        if (result.hasErrors()) {
            model.addAttribute("error", result.getAllErrors().get(0).getDefaultMessage());
            //1. 渲染 单选框
            List<Dict> typeList = applyMapper.listType();
            model.addAttribute("typeList", typeList);
            return "add";
        }

        //报销金额支持小数点2位
        if (!NumberUtil.isNumber(applyInfo.getAmount())) {
            model.addAttribute("error", "报销金额必须为数值");
            //1. 渲染 单选框
            List<Dict> typeList = applyMapper.listType();
            model.addAttribute("typeList", typeList);
            return "add";
        }
        //保留两位小数
        String roundStr = NumberUtil.roundStr(applyInfo.getAmount(), 2);
        applyInfo.setAmount(roundStr);

        applyService.add(applyInfo);

        return "redirect:list.do";

    }

}
